#!/usr/bin/env node

require('dotenv').config();
const net = require('net');
const chalk = require('chalk');

async function manualFTPTest() {
    console.log(chalk.blue('🔧 手动FTP协议测试'));
    
    const socket = new net.Socket();
    let response = '';
    
    socket.on('data', (data) => {
        response += data.toString();
        console.log(chalk.gray('< ' + data.toString().trim()));
    });
    
    socket.on('error', (err) => {
        console.error(chalk.red('Socket错误:'), err.message);
    });
    
    socket.on('close', () => {
        console.log(chalk.yellow('连接已关闭'));
    });
    
    return new Promise((resolve, reject) => {
        socket.connect(parseInt(process.env.FTP_PORT) || 21, process.env.FTP_HOST, async () => {
            console.log(chalk.green('✅ 已连接到FTP服务器'));
            
            // 等待欢迎消息
            await sleep(1000);
            
            // 发送用户名
            console.log(chalk.cyan(`> USER ${process.env.FTP_USER}`));
            socket.write(`USER ${process.env.FTP_USER}\r\n`);
            await sleep(1000);
            
            // 发送密码
            console.log(chalk.cyan(`> PASS ****`));
            socket.write(`PASS ${process.env.FTP_PASSWORD}\r\n`);
            await sleep(2000);
            
            // 测试PWD命令
            console.log(chalk.cyan('> PWD'));
            socket.write('PWD\r\n');
            await sleep(1000);
            
            // 退出
            console.log(chalk.cyan('> QUIT'));
            socket.write('QUIT\r\n');
            await sleep(1000);
            
            socket.end();
            resolve();
        });
        
        socket.setTimeout(15000);
        socket.on('timeout', () => {
            console.error(chalk.red('连接超时'));
            socket.destroy();
            reject(new Error('连接超时'));
        });
    });
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

manualFTPTest().catch(console.error);